package net.lesscoding.server.handler;

import cn.hutool.core.util.StrUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import net.lesscoding.message.GroupCreateRequestMessage;
import net.lesscoding.message.GroupCreateResponseMessage;
import net.lesscoding.session.Group;
import net.lesscoding.session.GroupSession;
import net.lesscoding.session.SessionFactory;

import java.util.List;
import java.util.Set;

/**
 * @author eleven
 * @date 2024/10/31 16:21
 * @apiNote
 */
@ChannelHandler.Sharable
public class GroupCreateRequestMessageHandler extends SimpleChannelInboundHandler<GroupCreateRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupCreateRequestMessage msg) throws Exception {
        String groupName = msg.getGroupName();
        Set<String> members = msg.getMembers();
        GroupSession groupSession = SessionFactory.groupSession();
        Group group = groupSession.createGroup(groupName, members);

        if (group == null) {
            ctx.writeAndFlush(new GroupCreateResponseMessage(false, groupName + "群聊已经存在"));
        } else {
            ctx.writeAndFlush(new GroupCreateResponseMessage(true, groupName + "创建成功"));
            // 发送拉群消息
            List<Channel> membersChannel = groupSession.getMembersChannel(groupName);
            for (Channel channel : membersChannel) {
                if (channel != null) {
                    channel.writeAndFlush(new GroupCreateResponseMessage(true, StrUtil.format("您已被拉入群聊{}", group)));
                }
            }
        }
    }
}
